package com.example.filedownload;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

@RestController
public class FileDownloadController {

    @GetMapping("/download/{filename}")
    public void downloadFile(@PathVariable String filename, HttpServletResponse response) throws IOException {
        Resource resource = getFileResource(filename);
        if (resource.exists() || resource.isReadable()) {
            String contentType = "application/octet-stream";
            String headerKey = "Content-Disposition";
            String headerValue = "attachment; filename=\"" + resource.getFilename() + "\"";

            response.setContentType(contentType);
            response.setHeader(headerKey, headerValue);

            try (FileInputStream fis = new FileInputStream(resource.getFile())) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = fis.read(buffer)) != -1) {
                    response.getOutputStream().write(buffer, 0, bytesRead);
                }
            }
        } else {
            throw new FileNotFoundException("File not found or not readable");
        }
    }

    private Resource getFileResource(String filename) {
        // 根据实际情况替换路径
        return new FileSystemResource("D:/soft/" + filename);
    }
}
